package com.local.admin.interceptor;

import com.local.admin.constants.AdminConstants;
import com.local.admin.pojo.AdminUser;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 后台拦截器
 */
@Component
public class AdminInterceptor implements HandlerInterceptor {

    /**
     * 后台拦截器，验证登录
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        //查询session是否保存了用户信息
        Object adminLoginUser = session.getAttribute(AdminConstants.ADMIN_USER_SESSION_KEY);
        if (Objects.isNull(adminLoginUser)) { //adminLoginUser中保存的是用户名
            session.setAttribute("errorMsg", "请先登录");
            response.sendRedirect(request.getContextPath() + "/admin/login");
            return false;
        } else {
            session.removeAttribute("errorMsg");
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
